//
//  ListView.swift
//  TodoList
//
//  Created by 刘圣洁 on 2025/6/12.
//

import SwiftUI

struct ListView: View {
    
    @EnvironmentObject var vm: ListViewModel
    @Environment(\.editMode) private var editMode
    @State private var isEdting = false
    
    var body: some View {
        ZStack {
            if vm.items.isEmpty {
                NoItemsView()
                    .transition(AnyTransition.opacity.animation(.easeIn))
            }else{
                List {
                    ForEach(vm.items) { item in
                        ListRowView(item: item)
                            .onTapGesture {
                                withAnimation(.linear) {
                                    vm.updateItem(item: item)
                                }
                            }
                    }
                    .onDelete(perform: vm.deleteItem)
                    .onMove(perform: vm.moveItem)
                }
                .listStyle(.plain)
                .toolbar{
                    ToolbarItem(placement: .topBarLeading) {
                        Button(isEdting ? "完成" : "编辑") {
                            toggleEditMode()
                        }
                    }
                }
                .toolbar{
                    ToolbarItem(placement: .topBarTrailing) {
                        NavigationLink("添加") {
                            AddView()
                        }
                    }
                }
                .environment(\.editMode, .constant(isEdting ? .active : .inactive))
            }
        }
        .navigationTitle("待办列表 📝")
        
    }
    
    
}

#Preview {
    NavigationStack {
        ListView()
    }
    .environmentObject(ListViewModel())
}

// MARK: - 函数部分
extension ListView{
    
//    更换列表编辑状态
    private func toggleEditMode() {
        withAnimation(.spring()) {
            isEdting.toggle()
        }
    }
    
}
